package net.hserver.sync.event;

import cn.hserver.core.ioc.IocUtil;
import cn.hserver.core.ioc.annotation.queue.QueueHandler;
import cn.hserver.core.ioc.annotation.queue.QueueListener;
import cn.hserver.core.queue.HServerQueue;
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import net.hserver.sync.config.EventConst;
import net.hserver.sync.config.FileState;
import net.hserver.sync.config.LogLevel;
import net.hserver.sync.config.LogType;
import net.hserver.sync.driver.WebDavDriver;
import net.hserver.sync.util.PathUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

@Slf4j
@QueueListener(queueName = EventConst.REMOTE_CHANGE_EVENT)
public class RemoteChangeEvent {

    @QueueHandler
    public void change(String webDavId, FileState fileState,String remotePath, String localPath) {
        WebDavDriver driver = IocUtil.getBean(webDavId, WebDavDriver.class);
        if (driver == null) {
            return;
        }
        try {
            if (fileState==FileState.onFileCreate) {
                InputStream inputStream = driver.get(remotePath);
                File parentFile = new File(localPath).getParentFile();
                parentFile.mkdirs();
                FileUtil.writeFromStream(inputStream, localPath);
                HServerQueue.sendQueue(EventConst.LOG_EVENT, LogLevel.SUCCESS, LogType.FILE_DOWNLOAD, localPath);
            }
            if (fileState==FileState.onFileDelete) {
                FileUtil.del(localPath);
                HServerQueue.sendQueue(EventConst.LOG_EVENT, LogLevel.SUCCESS, LogType.FILE_DELETE, localPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
            HServerQueue.sendQueue(EventConst.LOG_EVENT, LogLevel.ERROR, LogType.OTHER, e.getMessage());
        }
    }

}
